<?php

/**
 * Created by IntelliJ IDEA.
 * User: Janpoem
 * Date: 2015-04-19
 * Time: 13:58
 */
class Brothen
{

    private static $loadConfig = false;

    private static $config = array(
        'name' => 'AutoProxy 0.2.9',
        'glist_url' => 'http://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt',
        'token' => null,
        'token_field' => 't',
        'action_field' => 'a',
        'white_list' => array(),
        'through_list' => array(),
    );

    private static $glist = null;

    public static function mkPath($path)
    {
        return APP_ROOT . '/' . trim($path, '/');
    }

    public static function loadConfig()
    {
        if (!self::$loadConfig) {
            self::$loadConfig = true;
            $config = static::import(static::mkPath('config/config.php'));
            if (is_array($config) && !empty($config)) {
                self::$config = array_merge(self::$config, $config);
                return true;
            }
        }
        return false;
    }

    public static function import($path)
    {
        if (is_file($path) && is_readable($path))
            return require $path;
        return false;
    }

    public static function getConfig($key, $default = null)
    {
        if (!self::$loadConfig)
            static::loadConfig();
        if (isset(self::$config[$key]))
            return self::$config[$key];
        return Util::depthQuery(self::$config, $key, $default);
    }

    public static function setGList(GList $glist)
    {
        if (!isset(self::$glist))
            self::$glist = $glist;
    }

    public static function getGList()
    {
        if (!isset(self::$glist) || !(self::$glist instanceof GList)) {
            self::$glist = new GList(static::getConfig('glist_url'));
        }
        return self::$glist;
    }

    public static function verifyToken()
    {
        $field = static::getConfig('token_field', 'token');
        $token = static::getConfig('token', null);
        if (empty($_GET[$field]) || empty($token) || $token !== $_GET[$field])
            return false;
        return true;
    }
}